<script setup lang="ts">
import { ref, onMounted, onUpdated } from "vue"
import { GlobalInfo } from "../GlobalInfo";
import { DocService } from "../apis/DocService";
import { useRoute, onBeforeRouteUpdate } from "vue-router"
const text = ref("")
const isEditing = GlobalInfo.isEditing;
const isLoading = ref(false);
const isShowLoading = ref(false);

const preview: any = ref(null);
const containerEle = ref(<HTMLElement><unknown>null);
const route = useRoute();
var docId = route.params.id;
var version = route.params.version;
var showsubtitles = route.params.showsubtitles;
var docChanged = false;

const loadContent = async () => {    
    GlobalInfo.CurrentDocId.value = <any>docId;
    GlobalInfo.SubMenus.splice(0, GlobalInfo.SubMenus.length);

    GlobalInfo.ScrollToActiveItemFun();

    isLoading.value = true;
    window.setTimeout(()=>{
        if(isLoading.value){
            isShowLoading.value = true;
        }
    } , 1000);
    try{
        text.value = await DocService.GetDocContent(docId, version);
        
    }
    catch(e){
        GlobalInfo.showError(e);
    }
    finally{
        isLoading.value = false;
        isShowLoading.value = false;
    }
    
}

onBeforeRouteUpdate((to, from) => {
    containerEle.value.scrollTo(0,0);
    
    docId = to.params.id;
    version = to.params.version;
    showsubtitles = to.params.showsubtitles;
    console.log("路由变更，docid:", docId);
    loadContent();
});


onMounted(() => {
    loadContent();
});

const onChanged = ((text:any,html:any)=>{
    docChanged = true;
});

onUpdated(() => {
    if(!docChanged)
    return;

    const anchors = preview.value.$el.querySelectorAll('h2');
    const titles = Array.from(anchors).filter((title: any) => !!title.innerText.trim());

    var titleObjs = titles.map((el: any) => ({
        title: el.innerText,
        lineIndex: el.getAttribute('data-v-md-line')
    }));
    
    GlobalInfo.SubMenus.splice(0, GlobalInfo.SubMenus.length);
    if (showsubtitles !== "0") {
        GlobalInfo.SubMenus.push(...titleObjs);
    }

    GlobalInfo.Preview = preview.value;
    docChanged = false;
});
</script>

<template>
    <div class="root">
        <div class="container" ref="containerEle">
            <div class="loading" v-show="isShowLoading">正在加载...</div>
            <v-md-preview ref="preview" @change="onChanged" :text="text"></v-md-preview>
        </div>
    </div>
</template>

<style scoped>
.root {
    height: 100%;
    flex: 1;
    position: relative;
}

.container {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    overflow-y: auto;
}
</style>